<?php

class openapi_api_function_v1_login extends openapi_api_function_base implements openapi_api_function_interface {

    public function success($params, &$code, &$sub_msg) {
        $_GET['sess_id'] = empty($params['login_token']) ? (md5($_SERVER['SERVER_ADDR'] . base_request::get_remote_addr() . uniqid() . mt_rand(0, 9999))) : $params['login_token'];
        kernel::single('base_session')->start();
        $login_name = trim($params['login_name']);
        $login_password = trim($params['login_password']);
        if (! empty($login_name)) {
            // 返回re为用户名，支持邮箱登录
            $re = kernel::service('b2c_member_login')->checkuname($login_name);
            if ($re != '0') { // 用户名存在
                $rows = app::get('pam')->model('account')->getList('account_id', array(
                    'account_type' => 'member',
                    'disabled' => 'false',
                    'login_name' => $re,
                    'login_password' => pam_encrypt::get_encrypted_password($login_password, pam_account::get_account_type(app::get('b2c')->app_id), array(
                        'login_name' => $login_name
                    ))
                ));
                // 不同用户用同一个token登录时清除session数据
                if ($rows[0]['account_id'] != $_SESSION['account'][pam_account::get_account_type(app::get('b2c')->app_id)]) {
                    unset($_SESSION);
                }
                if ($rows) {
                    $_SESSION['account'][pam_account::get_account_type(app::get('b2c')->app_id)] = $rows[0]['account_id'];
                    $_SESSION['type'] = pam_account::get_account_type(app::get('b2c')->app_id);
                    $_SESSION['login_time'] = time();
                    // 判断是否提交审核通过
                    $member = app::get('b2c')->model('members')->getRow('*', array(
                        'member_id' => $rows[0]['account_id']
                    ));
                    if ($member['seller'] == 'seller') {
                        // 卖家审核
                        $storemanger = app::get('business')->model('storemanger')->dump(array(
                            'account_id' => $rows[0]['account_id']
                        ));
                        if (empty($storemanger) || empty($storemanger['store_idcardname'])) {
                            return $this->apiData(false, array(
                                'login_token' => kernel::single('base_session')->sess_id(),
                                'seller' => $member['seller']
                            ), 501, app::get('b2c')->_('请填写资料'));
                        }
                        if ($storemanger['approved'] != 1) {
                            if ($storemanger['approved'] == 0) {
                                return $this->apiData(false, array(
                                    'login_token' => kernel::single('base_session')->sess_id(),
                                    'seller' => ''
                                ), 502, app::get()->_('资料未审核'));
                            } else {
                                return $this->apiData(false, array(
                                    'login_token' => kernel::single('base_session')->sess_id(),
                                    'seller' => ''
                                ), 503, app::get()->_('资料审核未通过'));
                            }
                        }
                    }
                    // 获取购物车和收藏数量
                    $now_cart = app::get('b2c')->model('cart')->get_objects();
                    $result['login_token'] = kernel::single('base_session')->sess_id();
                    $_SESSION['CART_COUNT'] = $result['CART_COUNT'] = $now_cart['_cookie']['CART_COUNT'];
                    $_SESSION['CART_NUMBER'] = $result['CART_NUMBER'] = $now_cart['_cookie']['CART_NUMBER'];
                    $member_goods = app::get('b2c')->model('member_goods');
                    $fav_num = $member_goods->count(array(
                        'member_id' => $rows[0]['account_id']
                    ), 'fav');
                    $_SESSION['fav_num'] = $result['fav_num'] = $fav_num;
                    $mdl_salesman = app::get('business')->model('salesman');
                    $salesman = $mdl_salesman->getList('*', array(
                        'member_id' => $rows[0]['account_id'],
                        'status' => '1'
                    ));
                    if (! empty($salesman)) {
                        $result['seller'] = 'promoter';
                    } else {
                        $result['seller'] = $member['seller'];
                    }
                    $_SESSION['seller'] = $result['seller'];
                    // 购物车显示项目数或者商品数
                    $cart_show_type = app::get('site')->model('widgets_instance')->getRow('params', array(
                        'widgets_type' => 'index_cart'
                    ));
                    if ($cart_show_type['params']['cart_show_type'] == '2') {
                        $result['CART_NUMBER'] = $result['CART_COUNT'];
                    }
                    // 获取各种数据
                    $this->getMemberData($rows[0]['account_id'], $result);
                    return $this->apiData(true, $result, 200, app::get('b2c')->_('登陆成功'));
                } else {
                    return $this->apiData(false, null, 400, app::get('b2c')->_('用户名或密码错误'));
                }
            } else {
                return $this->apiData(false, null, 400, app::get('b2c')->_('用户不存在'));
            }
        } else {
            return $this->apiData(false, null, app::get('b2c')->_('用户名不能为空'));
        }
    }

    function getMemberData($member_id, &$result) {
        // 获取未读消息数
        $oMsg = kernel::single('b2c_message_msg');
        $no_read = $oMsg->getList('comment_id', array(
            'to_id' => $member_id,
            'has_sent' => 'true',
            'for_comment_id' => 'all',
            'inbox' => 'true',
            'mem_read_status' => 'false'
        ));
        $result['no_read'] = count($no_read);
    }

    public function logout($params, &$code, &$sub_msg) {
        $_GET['sess_id'] = $params['login_token'];
        kernel::single('base_session')->start();
        
        $auth = pam_auth::instance(pam_account::get_account_type(app::get('b2c')->app_id));
        foreach (kernel::servicelist('passport') as $k => $passport) {
            $passport->loginout($auth);
        }
        foreach (kernel::servicelist('member_logout') as $service) {
            $service->logout();
        }
        if ($uc = kernel::service("uc_user_synlogout")) {
            $uc->uc_user_synlogout();
        }
        app::get('b2c')->model('cart_objects')->setCartNum($arr);
        // unset($_SESSION['account'][pam_account::get_account_type(app::get('b2c')->app_id)]);
        return $this->apiData(true, null, 200, app::get('b2c')->_('成功登出'));
    }

    public function lost($params, &$code, &$sub_msg) {
        if (empty($params['email'])) {
            return $this->apiData(false, null, 400, app::get('b2c')->_('邮箱必填'));
        }
        $mailexists = app::get('b2c')->model('members')->is_exists_email($params['email']);
        if (! $mailexists) {
            return $this->apiData(false, null, 400, app::get('b2c')->_('邮箱不存在'));
        }
        // todo 发送验证邮件
        $member = app::get('b2c')->model('members')->dump(array(
            'email'
        ));
        if (empty($member)) {
            return $this->apiData(false, null, 400, app::get('b2c')->_('邮箱不存在'));
        }
        $account = app::get('pam')->model('account')->getList('*', array(
            'account_id' => $member['pam_account']['account_id']
        ));
        $message = $this->sendPSW($account[0]['account_id'], $params['email'], $account[0]['login_name'], $account[0]['createtime']);
        return $this->apiData(true, null, 200, $message);
    }

    function sendPSW($member_id, $email, $login_name, $createtime) {
        $objRepass = app::get('b2c')->model('member_pwdlog');
        $secret = $objRepass->generate($member_id);
        
        $sdf = app::get('pam')->model('account')->dump($member_id);
        $new_password = $this->randomkeys(6);
        $use_pass_data['login_name'] = $login_name;
        $use_pass_data['createtime'] = $createtime;
        
        $sdf['login_password'] = pam_encrypt::get_encrypted_password(trim($new_password), pam_account::get_account_type($this->app->app_id), $use_pass_data);
        
        if ($member_object = kernel::service("uc_user_edit")) {
            $aData['member_id'] = $member_id;
            $aData['passwd_re'] = $new_password;
            if (! $member_object->uc_user_edit_pwd($aData)) {
                return app::get('b2c')->_('第三方修改密码失败,请重试');
            }
        }
        
        if (app::get('pam')->model('account')->save($sdf)) {
            if ($this->send_email($login_name, $email, $new_password, $member_id)) {
                return app::get('b2c')->_('密码变更邮件已经发送到') . $email . app::get('b2c')->_('，请注意查收');
            } else {
                return app::get('b2c')->_('发送失败，请与商家联系');
            }
        } else {
            return app::get('b2c')->_('发送失败，请与商家联系');
        }
    }

    // ###随机取6位字符数
    function randomkeys($length) {
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyz'; // 字符池
        for ($i = 0; $i < $length; $i++) {
            $key .= $pattern{mt_rand(0, 35)}; // 生成php随机数
        }
        return $key;
    }

    // 发送验证邮件
    function send_email($login_name, $user_email, $new_password, $member_id) {
        $ret = app::get('b2c')->getConf('messenger.actions.account-lostPw');
        $ret = explode(',', $ret);
        
        if (! in_array('b2c_messenger_email', $ret))
            return false;
        $data['uname'] = $login_name;
        $data['passwd'] = $new_password;
        $data['email'] = $user_email;
        $obj_account = app::get('b2c')->model('member_account');
        return $obj_account->fireEvent('lostPw', $data, $member_id);
    }

    // 发送验证码
    function getRecoverMobileCode($mobile) {
        $objmember = app::get('b2c')->model('members');
        $objaccount = app::get('b2c')->model('member_account');
        $mobile = trim($mobile);
        
        if ($objmember->check_login_mobile($mobile, $message)) {
            // 验证是否是恶意请求验证码
            $request_time = time();
            $isSpite = app::get('b2c')->model('message_log')->isSpiteRequest($request_time, $mobile, $msg);
            if ($isSpite != 'ok') {
                if ($isSpite == 'spite') {
                    $message_log = app::get('b2c')->model('message_log')->saveMessageLog(__FUNCTION__, $request_time, $mobile, base_request::get_remote_addr(), 'spite', 'sms'); // 恶意请求 记录日志
                }
                return $this->apiData(false, null, 400, app::get('b2c')->_('请求错误'));
            }
            
            $random = $this->randCode();
            $_SESSION['MOBILE_CODE'] = $random;
            
            $data['contact']['phone']['mobile'] = $mobile;
            $data['mobile_code'] = $random;
            $data['sendmobilecodetype'] = 'userRegister';
            $data['disabled_time'] = 2;
            
            $message_log = app::get('b2c')->model('message_log')->saveMessageLog(__FUNCTION__, $request_time, $mobile, base_request::get_remote_addr(), 'ok', 'sms'); // 正常请求 记录日志
            
            $tmp_rs = $objaccount->fireEvent('sendmobilecode', $data);
            
            if ($tmp_rs) {
                return $this->apiData(true, null, 200, app::get('b2c')->_('success'));
            } else {
                return $this->apiData(false, null, 400, app::get('b2c')->_('短信发送失败，请重新获取验证码'));
            }
        } else {
            return $this->apiData(false, null, 400, app::get('b2c')->_($message));
        }
    }

    function randCode($len = 6) {
        $chars = '0123456789';
        mt_srand((double) microtime() * 1000000 * getmypid());
        $code = '';
        while (strlen($code) < $len)
            $code .= substr($chars, (mt_rand() % strlen($chars)), 1);
        return $code;
    }
}